import type { TodayRecommendItem } from "types/app-config";
import { nextTick } from "vue";
import Sortable from "sortablejs";

const SERVER_URL = import.meta.env.VITE_SERVER_URL;

export function useColumns(options: {
  onEdit?: (row: TodayRecommendItem, index: number) => void;
  onDelete?: (row: TodayRecommendItem, index: number) => void;
  onRowDrop?: (event: Sortable.SortableEvent) => void;
}) {
  const rowDrop = (event: { preventDefault: () => void }) => {
    event.preventDefault();
    nextTick(() => {
      const wrapper: HTMLElement = document.querySelector(
        ".el-table__body-wrapper tbody"
      );
      Sortable.create(wrapper, {
        animation: 300,
        handle: ".drag-btn",
        onEnd: event => {
          if (options.onRowDrop) options.onRowDrop(event);
        }
      });
    });
  };

  const columns: TableColumnList = [
    {
      width: 60,
      cellRenderer: () => (
        <iconify-icon-online
          icon="icon-park-outline:drag"
          class="drag-btn cursor-grab"
          onMouseenter={(event: { preventDefault: () => void }) =>
            rowDrop(event)
          }
        />
      )
    },
    {
      label: "标题",
      prop: "title"
    },
    {
      label: "标签",
      prop: "tag",
      cellRenderer: ({ row }) => <el-tag>{row.tag}</el-tag>
    },
    {
      label: "封面",
      prop: "images",
      width: 140,
      cellRenderer: ({ row }) => {
        if (row.flower.images && row.flower.images.length > 0) {
          return (
            <el-image
              style="width: 100%; height: 80px"
              src={SERVER_URL + row.flower.images[0]}
              fit="cover"
              preview-src-list={[SERVER_URL + row.flower.images[0]]}
              preview-teleported={true}
            />
          );
        }
        return <></>;
      }
    },
    {
      label: "价格",
      prop: "material",
      cellRenderer: ({ row }) => <>{"￥" + row.flower.price}</>
    },
    {
      label: "操作",
      width: 160,
      fixed: "right",
      cellRenderer: ({ index, row }) => (
        <>
          <el-button size="small" onClick={() => handleEdit(row, index)}>
            编辑
          </el-button>

          <el-popconfirm
            title="确认删除?"
            placement="top-end"
            onConfirm={() => handleDelete(row, index)}
          >
            {{
              reference: () => (
                <el-button size="small" type="danger" disabled={row.count > 0}>
                  删除
                </el-button>
              )
            }}
          </el-popconfirm>
        </>
      )
    }
  ];

  async function handleEdit(row, index: number) {
    if (options.onEdit) {
      options.onEdit(row, index);
    }
  }

  async function handleDelete(row, index: number) {
    if (options.onDelete) {
      options.onDelete(row, index);
    }
  }

  return {
    columns
  };
}
